<template>
  <div class="cg-form-item" :class="[]">
    <div class="cg-form-item-wrap" :style="wrapStyle">
      <label>{{ label }}</label>
    </div>
    <div class="cg-form-item-content" :style="contentStyle">
      <slot></slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance } from "vue"
import Emitter from "../../tools/emitter"

// 定义组件名称
defineOptions({
  name: "cg-form-item",
})

// 定义props
const props = withDefaults(defineProps<{
  label: string | undefined
}>(), {
  label: undefined
})

// 获取当前组件实例
const instance = getCurrentInstance()

// 手动实现查找父组件功能
function findParent(componentName: string) {
  if (!instance) return null

  let current = instance.parent
  while (current) {
    // 检查组件名称是否匹配
    if (current.type.name === componentName) {
      return current
    }
    current = current.parent
  }
  return null
}

// 计算属性
const labelWidth = computed(() => {
  const parent: any = findParent("cg-form")
  if (parent) {
    return parent.labelWidth
  }
  return 80
})

const wrapStyle = computed(() => ({
  width: labelWidth.value + "px"
}))

const contentStyle = computed(() => ({
  marginLeft: labelWidth.value + "px"
}))
</script>../../tools/emitter